<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @since         0.2.9
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace App\Controller;

use Cake\Controller\Controller;
use Cake\Event\Event;
use Cake\Network\Session;

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @link http://book.cakephp.org/3.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {
    public $helpers = ['Form', 'Html', 'Time'];
    public $acc;
/**
 * Initialization hook method.
 *
 * Use this method to add common initialization code like loading components.
 *
 * @return void
 */
	public function initialize() {
		$this->loadComponent('Flash');
	}
    public function beforeFilter(Event $event){
        parent::beforeFilter($event);
        if ($this->request->params['controller'] != 'Accounts' || $this->request->params['action'] != 'login') {
            $this->acc = $this->getAccountInfo();
            if ($this->acc == null) {
                $this->setLoginRedirectURL();
                $this->redirect('/Accounts/login');
            } else {
                $this->set('role', $this->acc['role_id']);
                $this->set('acc',$this->acc);
            }
        } else if ($this->request->params['controller'] == 'Accounts' || $this->request->params['action'] == 'logout') {
            $this->request->session()->write('REQUEST_URL', null);
            $this->request->session()->write('LOGIN_USER', null);
        }
    }
    public function beforeRender(Event $event){
        parent::beforeRender($event);
    }
    function setLoginRedirectURL ()
    {
        $link = '/' . $this->params['controller'] . '/' . $this->params['action'];
        $this->request->session()->write('TMS_REQUEST_URL', $link);
    }
    public function getAccountInfo(){
        return $this->request->session()->read('TMS_LOGIN_USER');
    }
    public function setAccountInfo($account){
        $this->request->session()->write('TMS_LOGIN_USER', $account);
    }
    function generateRandomString ($length = 10)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }

}
